import re
from glob import glob

import pandas as pd
from tqdm import tqdm
from utils.post_process import post_process

# 统一为英文符号
def ch_en(word):
        # 统一为英文符号
        intab = u"！—。【】“”‘’《》—「」『』〖〗〔〕〓︰﹒﹕﹙﹚﹝﹞﹢〈〉∽∶‥–‒Ι×[]（）＃［］{}：％＊﹛﹜，－／÷＿﹡；ⅹ\\"
        outab = u"!-.()\"\"\'\'()-()()()()=:.:()()+()~::--i*()()#()():%*(),-//_*;*/"
        trantab = str.maketrans(intab, outab)  # 一一映射。
        word = word.translate(trantab)  # 返回字符串S的副本，其中每个字符都已通过给定的转换表进行映射。
        # 统一罗马数字
        word = word.replace("Ⅰ", "I")
        word = word.replace("Ⅱ", "II")
        word = word.replace("Ⅲ", "III")
        word = word.replace("Ⅳ", "IV")
        word = word.replace("Ⅴ", "V")
        word = word.replace("Ⅵ", "VI")
        word = word.replace("Ⅶ", "VII")
        word = word.replace("Ⅷ", "VIII")
        word = word.replace("Ⅸ", "IX")
        word = word.replace("Ⅹ", "X")

        if re.findall("＜.*?＞", word):
            word = word.replace("＜", "(")
            word = word.replace("＞", ")")
        if re.findall("<.*?>", word):
            word = word.replace("<", "(")
            word = word.replace(">", ")")
        # 空格处理
        word = re.sub(
            "(?<=[^0-9a-zA-Z])[ ]+(?=[0-9a-zA-Z])|(?<=[0-9a-zA-Z])[ ]+(?=[^0-9a-zA-Z])|"
            "(?<=[^0-9a-zA-Z])[ ]+(?=[^0-9a-zA-Z])|(?<=[()])[ ]+|[ ]+(?=[()\-])",
            "", word)
        return word


def file_process(path):
    xl_path = path
    df = pd.read_excel(xl_path, dtype=str, keep_default_na=False)
    # df["customer_name"] = df["customer_name"].apply(lambda y: ch_en(y))
    df = df.applymap(lambda y: ch_en(y))
    df.to_excel(xl_path.replace(".xlsx", "1.xlsx"), index=False)


# 后处理测试
def post_process_test():
    xl_path = "/home/kv/workspace/医院数据库/版本库入country库0.xlsx"
    df = pd.read_excel(xl_path, dtype=str, keep_default_na=False)
    table = []
    for index in tqdm(range(0, len(df), 200)):
        cache = []
        input_par = []
        for k in range(0, 200):
            if k + index >= len(df):
                continue
            # 医院网站库格式
            item = df.iloc[index + k, :]
            series = item.copy()
            full_name = item["full_name"]
            if full_name:
                # 后处理
                input_par.append(
                    {
                        "医院名称": "",
                        "费用名称": full_name,
                        "number": "",
                        "amount": "",
                        "mapping_name": ""
                    })
                cache.append(series)
            else:
                table.append(series)

        res = post_process(input_par)
        for k in range(0, len(res)):
            customer_name = res[k]["mapping_name"]
            full_name = res[k]["name"]
            series = cache[k]
            if customer_name:
                series["customer_name"] = customer_name
            table.append(series)
    df1 = pd.DataFrame(table).fillna("")
    df1.to_excel(xl_path.replace(".xlsx", "_测试.xlsx"), index=False)


if __name__ == '__main__':
    paths = glob("/home/kv/*.xlsx")
    for path in tqdm(paths):
        file_process(path)
    # post_process_test()